# -*- coding: utf-8 -*-
"""
数据填报部分
    一流大学数据填报账户
    一流学科数据填报账号
"""

from flask import Blueprint, request, jsonify, send_from_directory, current_app
from flask_login import login_required
import os
from openpyxl import load_workbook, Workbook
import json
from models import File, Subject
import zipfile
from app import db


download = Blueprint('download', __name__)


@download.route('/download/example')
@login_required
def download_example():
    """
    1.当前样表是下载学校和学科的样表。
    2.后期可以根据来用户权限判断。
    :return:
    """
    return send_from_directory('./data/', filename="双一流大学+学科指标数据表格.zip")

@download.route('/download/handbook')
@login_required
def download_handbook():
    """
    下载操作手册
    """
    return send_from_directory("./data/",
                               filename="教育部“双一流”建设监测平台用户操作指南.docx",
                               as_attachment=True)


@download.route('/download/<point_id>')
@login_required
def load_point_template(point_id):
    """
    下载监控点样表文件
    :return:
    """
    base = 'data/template/'
    if point_id.startswith('D'):
        dir = 'university/'
    elif point_id.startswith('X'):
        dir = 'subject/'
    else:
        return jsonify({'status_code':404, "reason":"没找到该样表"})
    # 判断是否之前
    temp_file = os.path.join('data/temp_data/', point_id+'.xlsx')
    if os.path.exists(temp_file):
        return send_from_directory(directory='data/temp_data/', filename=point_id+'.xlsx',
                                   as_attachment=True)

    file_path = os.path.join(base, dir, point_id[:3]+'.xlsx')
    wb = load_workbook(file_path)
    backup_sheetname = point_id[:3] # 备用的sheetname
    for sheetname in wb.sheetnames:
        if sheetname != point_id and sheetname != backup_sheetname:
            ws = wb[sheetname]
            wb.remove(ws)
    if len(wb.sheetnames) == 2:
        wb.remove(wb[backup_sheetname]) # 删除备用的
    new_file = 'data/temp_data/' + point_id+'.xlsx'
    wb.save(new_file)
    return send_from_directory(directory='data/temp_data',
                               filename=point_id + '.xlsx',
                               as_attachment=True)


@download.route('/download/fill_data/<point_id>', methods=['GET'])
@login_required
def download_fill_data(point_id):
    """
    加载一流大学数据指标
    :return:
    """
    # request_data = json.loads(request.get_data().decode("utf-8"))
    subject = request.args.get('subject')
    file = File.query.filter_by(point=point_id, file_type=subject).first() # 查看文件
    if file:
        return send_from_directory(directory='./',
                                   filename=file.path,
                                   as_attachment=True,
                                   attachment_filename=file.name)
    else:
        return json.dumps({'status_code':404,
                            'reason':'文件没有找到.'})

def zip_ya(start_dir, file_new):
    start_dir = start_dir  # 要压缩的文件夹路径
    # file_news = start_dir + '.zip'  # 压缩后文件夹的名字

    z = zipfile.ZipFile(file_new, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(start_dir):
        f_path = dir_path.replace(start_dir, '')  # 这一句很重要，不replace的话，就从根目录开始复制
        f_path = f_path and f_path + os.sep or ''  # 实现当前文件夹以及包含的所有文件的压缩
        for filename in file_names:
            if filename.endswith('xlsx'):
                # 这边根据md5的文件名，获取其原来的文件名
                current_app.logger.info(filename)
                current_app.logger.info(dir_path)
                current_app.logger.info(f_path)
                sql = 'SELECT * FROM files WHERE path LIKE "%{0}%"'.format(filename)
                origin_file = db.session.execute(sql).first()
                if origin_file:
                    arcname = f_path + origin_file.name
                    z.write(os.path.join(dir_path, filename), arcname)
                # else:
                #     arcname = f_path + filename
                # z.write(os.path.join(dir_path, filename), arcname)
                # z.write(os.path.join(dir_path, filename), f_path + filename)
    z.close()
    return file_new

@download.route('/download/whole-data')
@login_required
def download_whole_data():
    # 先判断文件夹是否为空
    # files = File.query.all()
    sql = 'SELECT * FROM files'
    files = list(db.session.execute(sql))
    if not files:
        return json.dumps({"status_code":404, "reason":"尚未上传任何相关的监测指标文件"}, ensure_ascii=False)

    file_new = 'whole-data.zip'
    temp_file = os.path.join('data/temp_data/', file_new)
    if os.path.exists(temp_file):
        os.remove(temp_file)
    zip_ya('data/fill_data/', temp_file)
    return send_from_directory(directory='data/temp_data',
                               filename=file_new,
                               as_attachment=True,
                               attachment_filename="全部数据.zip")


@download.route('/download/whole-university-data')
@login_required
def download_whole_university_data():

    # files = File.query.filter_by(file_type="大学").all()
    sql = 'SELECT * FROM files WHERE file_type = "大学"'
    files = list(db.session.execute(sql))
    if not files:
        return json.dumps({"status_code":404, "reason":"尚未上传一流大学指标文件"}, ensure_ascii=False)

    file_new = 'whole-university-data.zip'
    temp_file = os.path.join('data/temp_data/', file_new)
    if os.path.exists(temp_file):
        os.remove(temp_file)
    zip_ya('data/fill_data/university/', temp_file)
    return send_from_directory(directory='data/temp_data',
                               filename=file_new,
                               as_attachment=True,
                               attachment_filename="全部大学数据.zip")


@download.route('/download/whole-subject-data')
@login_required
def download_whole_subject_data():

    sql = 'SELECT * FROM files WHERE file_type != "大学"'
    files = list(db.session.execute(sql))
    if not files:
        return json.dumps({"status_code":404, "reason":"尚未上传一流学科指标文件"}, ensure_ascii=False)

    file_new = 'whole-subject-data.zip'
    temp_file = os.path.join('data/temp_data/', file_new)
    if os.path.exists(temp_file):
        os.remove(temp_file)
    zip_ya('data/fill_data/subject/', temp_file)
    return send_from_directory(directory='./data/temp_data',
                               filename=file_new,
                               as_attachment=True,
                               attachment_filename="全部学科数据.zip")

@download.route('/download/subject-data')
@login_required
def download_subject_data():
    subject = request.args.get('subject')

    sql = 'SELECT * FROM files WHERE file_type = "%s"' % subject
    files = list(db.session.execute(sql))
    # files = File.query.filter_by(file_type=subject).all()
    if not files:
        return json.dumps({"status_code":404, "reason":"尚未上传当前学科指标文件"}, ensure_ascii=False)

    file_new = '%s-subject-data.zip' % subject
    temp_file = os.path.join('data/temp_data/', file_new)
    if os.path.exists(temp_file):
        os.remove(temp_file)
    zip_ya('data/fill_data/subject/%s/' % subject, temp_file)
    return send_from_directory(directory='./data/temp_data',
                               filename=file_new,
                               as_attachment=True,
                               attachment_filename="%s-学科数据.zip" % subject)

@download.route('/download/data-status')
@login_required
def data_status():
    status = {}

    # 所有的数据
    whole_data = File.query.all()
    if whole_data:
        status['whole_data'] = True
    else:
        status['whole_data'] = False

    # 所有的大学数据
    whole_un_data = File.query.filter_by(file_type="大学").all()
    if whole_un_data:
        status['whole_university_data'] = True
    else:
        status['whole_university_data'] = False

    # 所有的学科数据
    sql = 'SELECT * FROM files WHERE file_type != "大学"'
    whole_subject_data = list(db.session.execute(sql))
    if whole_subject_data:
        status['whole_subject_data'] = True
    else:
        status['whole_subject_data'] = False

    sub_status = {}
    subjects = Subject.query.all()
    subject_names = [sub.name for sub in subjects]
    for name in subject_names:
        sub_files = File.query.filter_by(file_type=name).all()
        if sub_files:
            sub_status[name] = True
        else:
            sub_status[name] = False
    status['subject_data'] = sub_status
    return json.dumps({"data": status}, ensure_ascii=False)



